package com.bigdata.scala.iterator

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

import com.alibaba.fastjson.JSONObject
import org.apache.commons.lang3.StringUtils

/**
 *
 * ${DESCRIPTION}
 *
 * @author Administrator
 * @version 1.0
 * @date 2021-12-12 14:25
 */
class BigDataMySQLIterator(
                          url: String,
                          userName: String,
                          password: String,
                          tableName: String,
                          sql: String = ""
                          ) extends Iterator[String]{

  private val conn: Connection = DriverManager.getConnection(url, userName, password)

  private val sqlStr = if(StringUtils.isNotBlank(sql)) sql else s"SELECT * FROM ${tableName}"

  private val pstmt: PreparedStatement = conn.prepareStatement(sqlStr)

  private val rs: ResultSet = pstmt.executeQuery()

  override def hasNext: Boolean = {
    rs.next()
  }

  override def next(): String = {

    val metaData = rs.getMetaData

    val columnCount = metaData.getColumnCount

    val jSONObject = new JSONObject()

    for(i <- 1 until columnCount){
      val columnName = metaData.getColumnName(i)

      val columnValue = rs.getObject(columnName)

      jSONObject.put(columnName, columnValue)
    }

    jSONObject.toJSONString
  }
}
